package dao;

import model.BorrowDetail;
import view.LoginFrm;

import javax.swing.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class bdetailDao {


    public ResultSet list(Connection con, BorrowDetail borrowDetail) throws SQLException{

        String sql ="select * from borrowdetail where  book_id =? ";
        PreparedStatement pstmt =(PreparedStatement) con.prepareStatement(sql);
        pstmt.setInt(1,borrowDetail.getBookId());

        ResultSet rs = pstmt.executeQuery();


        return rs;

    }

    public int add(Connection con, BorrowDetail borrowDetail) throws SQLException {

        String sql= "insert into borrowdetail (user_id,book_id,status,borrow_time,return_time) values(?,?,?,?,?)";

        PreparedStatement pstmt1 = con.prepareStatement(sql);

        pstmt1.setInt(1,borrowDetail.getUserId());
        pstmt1.setInt(2,borrowDetail.getBookId());
        pstmt1.setInt(3,borrowDetail.getStatus());
        pstmt1.setLong(4,borrowDetail.getBorrowTime());
        pstmt1.setLong(5,00000L);


        return pstmt1.executeUpdate();
        // return 0;
    }






    public List<BorrowDetail> selectAll(Connection con) throws SQLException {

        List<BorrowDetail> list=new ArrayList<>();


        String sql="select * from borrowdetail where user_id=?";

        PreparedStatement pstmt1 = con.prepareStatement(sql);
        pstmt1.setInt(1, LoginFrm.currentUser.getUserId());


        ResultSet rs = pstmt1.executeQuery();


        while(rs.next()){

            BorrowDetail b=new BorrowDetail();
            b.setUserId(rs.getInt("user_id"));
            b.setBookId(rs.getInt("book_id"));
            b.setStatus(rs.getInt("status"));
            b.setBorrowTime(rs.getLong("borrow_time"));
            b.setReturnTime(rs.getLong("return_time"));

            list.add(b);
        }

        return list;

    }


    public void removeByBookId(Connection con, String text) throws SQLException {

        String sql="delete from borrowdetail where book_id=? and user_id=?";


            PreparedStatement pstmt1 = con.prepareStatement(sql);
            pstmt1.setInt(1, Integer.parseInt(text));
            pstmt1.setInt(2, LoginFrm.currentUser.getUserId());

            pstmt1.executeUpdate();






    }






}
